package com.yxy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yxy.common.PageResult;
import com.yxy.context.BaseContext;
import com.yxy.mapper.RateMapper;
import com.yxy.mapper.RemarkMapper;
import com.yxy.mapper.UserMapper;
import com.yxy.pojo.dto.PageRemarkQueryDTO;
import com.yxy.pojo.dto.RemarkDTO;
import com.yxy.pojo.dto.TypeDTO;
import com.yxy.pojo.entity.Rate;
import com.yxy.pojo.entity.Remark;
import com.yxy.pojo.entity.User;
import com.yxy.pojo.vo.RemarkVO;
import com.yxy.service.RemarkService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Service
public class RemarkServiceImpl implements RemarkService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RemarkMapper remarkMapper;
    @Autowired
    private RateMapper rateMapper;

    /**
     * 写短评
     * @param remarkDTO
     */
    @Override
    public void writeReviews(RemarkDTO remarkDTO) {
        Remark remark = new Remark();
        BeanUtils.copyProperties(remarkDTO, remark);
        // 获取当前写评论的用户id
        int userId = BaseContext.getCurrentId();
        remark.setUserId(userId);
        remark.setCreateTime(LocalDate.now());
        remarkMapper.writeReviews(remark);
    }

    /**
     * 获取短评
     * @param pageRemarkQueryDTO
     * @return
     */
    @Override
    @Transactional
    public PageResult pageRemarkQuery(PageRemarkQueryDTO pageRemarkQueryDTO) {
        // 用mybatis的分页插件进行分页，设置当前页为pageRemarkQueryDTO.getPage()，每页显示条数为pageRemarkQueryDTO.getPageSize()
        PageHelper.startPage(pageRemarkQueryDTO.getPage(), pageRemarkQueryDTO.getPageSize());
        // 存放返回前端的集合
        List<RemarkVO> remarkVOList = new ArrayList<>();
        // 根据类型和类型id分页查询所有评论数据
        Page<Remark> page = remarkMapper.getReviews(pageRemarkQueryDTO);
        page.getResult().forEach(remark -> {
            RemarkVO remarkVO = new RemarkVO();
            // 根据用户id查询评论分数
            Rate rate = rateMapper.getRateByUserId(remark.getType(), remark.getTypeId(), remark.getUserId());
            if(rate == null){
                remarkVO.setRate(0);
            }else{
                remarkVO.setRate(rate.getRateVal());
            }
            // 根据用户id查询用户信息
            User user = userMapper.getById(remark.getUserId());
            remarkVO.setUserId(user.getId());
            remarkVO.setAvatar(user.getAvatar());
            remarkVO.setNickname(user.getNickName());
            remarkVO.setContent(remark.getContent());
            remarkVO.setTime(remark.getCreateTime());
            remarkVOList.add(remarkVO);
        });
        return new PageResult(page.getTotal(), remarkVOList);
    }
}
